package com.gongpingjialoan.activity.tool;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.widget.LoadingDialog;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 车辆违章查询
 *
 * @author Administrator
 */
public class LicenceActivity extends BaseActivity {

    private LicenceActivity mySelf = this;

    private TextView cityChoice;

    private TextView provForShort;

    private EditText platNumView;

    private EditText engiNumView, chejiaEditText;

    private Button backImg;

    private Button submit;

    private String city;

    private String plateNumber = null;

    private String engineNumber = null;

    private String chejiaNumber = null;

    private String provNameForShort = "苏";

    private static final int REQUEST_CITY = 0;

    private LinearLayout city_layout;

    private int type;

    private NetDataJson standardnetDataJson;

    private JSONObject jsonObject;

    private LoadingDialog loadingDialog;

    private boolean isNeedChejia = false;
    private boolean isNeedFadongji = false;

    private String province, city_pinyin;

    private int id;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_licence);
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            setTitle("绑定");
            id = getIntent().getIntExtra("id", 0);
        } else {
            setTitle("违章查询");
        }

        initBase(this);
        initView();
        setListeners();
        getStandardData();
        // initHistory();
    }

    private void getStandardData() {
        loadingDialog.show();
        standardnetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                loadingDialog.dismiss();
                Toast.makeText(LicenceActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                loadingDialog.dismiss();
                try {
                    jsonObject = json.getJSONObject("data");
                } catch (Exception e) {
                }
            }
        });
        standardnetDataJson.setUrl(API.standard_query);
        //缓存1天
        standardnetDataJson.setCacheTime(60 * 60 * 24);

        standardnetDataJson.request("get");

    }


    private void initView() {
        loadingDialog = new LoadingDialog(this);
        chejiaEditText = (EditText) findViewById(R.id.edit_chejia);
        cityChoice = (TextView) findViewById(R.id.choose_city);
        provForShort = (TextView) findViewById(R.id.prov_for_short);
        platNumView = (EditText) findViewById(R.id.edit_plat);
        engiNumView = (EditText) findViewById(R.id.edit_engine);
        submit = (Button) findViewById(R.id.button_submit);
        if (type == 1) {
            submit.setText("绑定");
        }
        city_layout = (LinearLayout) findViewById(R.id.city_layout);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                city = data.getExtras().getString("city");
                if (jsonObject != null) {
                    try {
                        JSONObject result = jsonObject.getJSONObject(city);
                        JSONArray mask = result.getJSONArray("mask");
                        provNameForShort = result.getString("licence_prefix");
                        province = result.getString("province");
                        city_pinyin = result.getString("city_pinyin");
                        int engiNum = mask.getInt(0);
                        int chejiaNum = mask.getInt(1);
                        engiNumView.setText("");
                        chejiaEditText.setText("");
                        platNumView.setText("");
                        provForShort.setVisibility(View.GONE);
                        if (engiNum == -1) {
                            isNeedFadongji = true;
                            engiNumView.setHint("请输入发动机号");
                            engiNumView.setEnabled(true);
                        } else if (engiNum == 0) {
                            isNeedFadongji = false;
                            engiNumView.setHint("无需输入发动机号");
                            engiNumView.setEnabled(false);
                        } else {
                            isNeedFadongji = true;
                            engiNumView.setHint("请输入发动机号后" + engiNum + "位");
                            engiNumView.setEnabled(true);
                        }
                        if (chejiaNum == -1) {
                            isNeedChejia = true;
                            chejiaEditText.setHint("请输入车架号");
                            chejiaEditText.setEnabled(true);
                        } else if (chejiaNum == 0) {
                            isNeedChejia = false;
                            chejiaEditText.setHint("无需输入车架号");
                            chejiaEditText.setEnabled(false);
                        } else {
                            isNeedChejia = true;
                            chejiaEditText.setHint("请输入车架号后" + chejiaNum + "位");
                            chejiaEditText.setEnabled(true);
                        }

                        cityChoice.setText(city);
                        provForShort.setVisibility(View.VISIBLE);
                        provForShort.setText(provNameForShort);
                    } catch (Exception e) {
                        showTips(1, "暂不支持该城市");
                    }


                }

                break;
            default:
                break;
        }
    }

    private void setListeners() {
        city_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LicenceActivity.this, CityActivity.class);
                startActivityForResult(intent, REQUEST_CITY);
            }
        });
        city_layout.requestFocus();

        platNumView.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View arg0, boolean arg1) {
                if (TextUtils.isEmpty(city)) {
                    showTips(0, "请选择城市");
                }
            }

        });

        engiNumView.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View arg0, boolean arg1) {
                if (TextUtils.isEmpty(city)) {
                    showTips(0, "请选择城市");
                }
            }

        });

        chejiaEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View arg0, boolean arg1) {
                if (TextUtils.isEmpty(city)) {
                    showTips(0, "请选择城市");
                }
            }

        });


        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(city)) {
                    showTips(2, "请选择城市");
                    return;
                }
                if (platNumView.getText().toString().trim().equals("")) {
                    showTips(2, "请输入车牌号");
                    return;
                }
                if (engiNumView.getText().toString().trim().equals("") && isNeedFadongji) {
                    showTips(2, "请输入发动机号");
                    return;
                }
                if (chejiaEditText.getText().toString().trim().equals("") && isNeedChejia) {
                    showTips(2, "请输入车架号");
                    return;
                }

                plateNumber = platNumView.getText().toString();
                engineNumber = engiNumView.getText().toString();
                chejiaNumber = chejiaEditText.getText().toString();

                if (type == 0) {
                    getLicenceInfo( plateNumber, engineNumber, chejiaNumber);
                } else {
                    bindCar(city, provNameForShort + plateNumber, engineNumber, chejiaNumber);
                }

            }

        });

    }


    private void bindCar(String city, String licencePlate, String engineNumber, String chejia) {
        loadingDialog.show();
        NetDataJson mNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {

            @Override
            public void onDataJsonError(String errorMessage) {
                // progressDialog.dismiss();
                loadingDialog.dismiss();
                // Toast.makeText(getApplicationContext(), errorMessage,Toast.LENGTH_SHORT).show();
                showTips(4, errorMessage);
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                loadingDialog.dismiss();
                showTips(4, "绑定成功！");
                setResult(Activity.RESULT_OK);
                finish();
            }
        });


        mNetDataJson.setUrl(API.bind_violation);
        mNetDataJson.addParam("my_car_id", id);
        mNetDataJson.addParam("license_plate", licencePlate);

        if (isNeedFadongji) {
            mNetDataJson.addParam("engine_no", engineNumber);
        }
        mNetDataJson.addParam("city", city);
        if (isNeedChejia) {
            mNetDataJson.addParam("vin", chejia);
        }
        mNetDataJson.request("post");
    }


    /**
     * 查询违章记录
     *
     * @param
     * @param licencePlate 车牌号 例：苏A30264
     * @param engineNumber 发送机号
     */
    private void getLicenceInfo( String licencePlate, String engineNumber, String chejia) {
        Intent intent = new Intent();
        intent.putExtra("license_num", licencePlate);
        intent.putExtra("licence_prefix", provNameForShort);
        intent.putExtra("province", province);
        if (isNeedFadongji) {
            intent.putExtra("engine_number", engineNumber);
        }
        intent.putExtra("city_pinyin", city_pinyin);
        if (isNeedChejia) {
            intent.putExtra("body_number", chejia);
        }
        intent.setClass(LicenceActivity.this, LicenceResultActivity.class);
        startActivity(intent);

//
//
//


//        return;
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
//        OpenHelperManager.releaseHelper();
    }

}
